﻿using System;
using System.Drawing;
using System.Windows.Forms;


namespace FolderSize
{
    public partial class MainWindow : Form
    {


        public MainWindow()
        {
            InitializeComponent();
            SystemVar.CurrentExePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            fbdFolder.SelectedPath = SystemVar.SelectedPath;
            if (fbdFolder.ShowDialog() == DialogResult.OK)
            {
                SystemVar.SelectedPath = fbdFolder.SelectedPath;
                StartProcess(SystemVar.SelectedPath);
            }
        }
        private void StartProcess(string rootPath)
        {
            try
            {
                tvFileTree.Nodes.Clear();
                FileTree rootNode = new FileTree(rootPath);
                rootNode.PhysicPath = (rootPath);
                this.Text = rootNode.ToString();

                Application.DoEvents();

                FileTreeHelper.GetFileCount(ref rootNode);
                TreeNode tvNode = new TreeNode(FileTreeNode2String(rootNode, ((double)rootNode.SizeWithChild / 1000000).ToString("F3").Length));
                tvNode.Tag = rootNode;
                FillTreeView(rootNode, tvNode);
                tvFileTree.Nodes.Add(tvNode);
                if (tvFileTree.Nodes.Count > 0)//展开一级
                    tvFileTree.Nodes[0].Expand();
            }
            catch (UnauthorizedAccessException ex)
            {
                if (MessageBox.Show("权限不足,是否尝试重新启动,错误信息:" + ex.Message, "权限错误", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //如果要求管理员权限，就重新启动
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    startInfo.UseShellExecute = true;
                    startInfo.Arguments = "\"" + rootPath + "\"";
                    startInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(SystemVar.CurrentExePath);
                    startInfo.FileName = SystemVar.CurrentExePath;

                    //设置启动动作,确保以管理员身份运行  
                    startInfo.Verb = "runas";
                    System.Diagnostics.Process.Start(startInfo);
                }
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void FillTreeView(FileTree rootFolder, TreeNode tvNode)
        {
            int maxFileSizeStringLength = 0;
            //获取文件大小字符串的最长长度,便于格式化
            foreach (FileTree t in rootFolder.Childs)
            {
                int currentLength = ((double)t.SizeWithChild / 1000000).ToString("F3").Length;
                if (currentLength > maxFileSizeStringLength)
                    maxFileSizeStringLength = currentLength;
            }

            foreach (FileTree t in rootFolder.Childs)
            {
                TreeNode tvSubNode = new TreeNode(FileTreeNode2String(t, maxFileSizeStringLength));
                tvSubNode.Tag = t;
                FillTreeView(t, tvSubNode);
                tvNode.Nodes.Add(tvSubNode);
            }
        }

        private string FileTreeNode2String(FileTree node, int maxFileSizeStringLength)
        {
            return string.Format("【{1," + maxFileSizeStringLength + ":0.000}MB】{0}", node.ToString(), (double)node.SizeWithChild / 1000000);
        }


        private void btnConfirm_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void TestWindow_Load(object sender, EventArgs e)
        {
            if (SystemVar.startSettingFolder != null && SystemVar.startSettingFolder.Length > 0)
            {
                StartProcess(SystemVar.startSettingFolder[0]);
            }
            cbExplorerContextMenu.Checked = WindowsHelper.GetContextMenu();

            rtxtReadme.Text = @"版本:" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            rtxtReadme.Text += "\nhttps://gitee.com/somereason/show-folder-size";
        }

        private void tvFileTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            FileTree tNode = ((FileTree)e.Node.Tag);
            rTxtInfo.Text = string.Format(@"占用空间{0:F3}MB
共有文件夹：{1}个
共有文件：{2}个
共有子文件{3}个，子文件夹{4}个
路径{5}
", ((double)tNode.SizeWithChild) / 1000000, tNode.FolderCountCurrent, tNode.FileCountCurrent, tNode.FileCountWithChild, tNode.FolderCountWithChild, tNode.PhysicPath);
        }

        #region Setting     

        private void cbExplorerContextMenu_CheckedChanged(object sender, EventArgs e)
        {
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                WindowsHelper.SetContextMenu(cbExplorerContextMenu.Checked);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void tvFileTree_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                TreeNode CurrentNode = tvFileTree.GetNodeAt(ClickPoint);
                if (CurrentNode != null)//判断你点的是不是一个节点
                {
                    CurrentNode.ContextMenuStrip = cmsTreeRightClick;
                    tvFileTree.SelectedNode = CurrentNode;//选中这个节点
                }
            }
        }

        private void tsmiOpen_Click(object sender, EventArgs e)
        {
            FileTree tNode = ((FileTree)tvFileTree.SelectedNode.Tag);
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = tNode.PhysicPath;
            p.Start();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            StartProcess(SystemVar.SelectedPath);
        }
    }
}
